﻿using BLL;
using DAL;
using Model;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.设置窗体;

namespace 纺织贸易管理系统.其他窗体
{
    public partial class 录入可发卷 : Sunny.UI.UIForm
    {
        public StockTable stock { get; set; }
        private BindingList<JuanHaoTable> juanHaoTables = new BindingList<JuanHaoTable>();

        public 录入可发卷()
        {
            InitializeComponent();
            gridView1.IndicatorWidth = 30;
            cmbmaitou.Items.AddRange(Tools.获取模板.获取所有模板(PrintPath.唛头模板).ToArray());
            加载架子();
            //this.juanHaoTables.AddingNew += (s, ev) => {
            //  ev.NewObject =(new JuanHaoTable() { PiHao = juanHaoTables.Count + 1 });
            //    gridControl1.RefreshDataSource();
            //};
        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            gridView1.SetRowCellValue(e.RowHandle, "PiHao", juanHaoTables.Count);
            gridControl1.RefreshDataSource();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var jlist = juanHaoTables.Where(x => x.PiHao == gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "PiHao").TryToInt()).ToList();
            if (jlist.Count > 1)
            {
                MessageBox.Show("该缸卷号一卷存在。缸卷号不能重复。请重新输入", this.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            txtheji.Text = juanHaoTables.Sum(x => x.biaoqianmishu).ToString();
            txthejijuanshu.Text = (juanHaoTables.Count).ToString();
        }

        private void 录入可发卷_Load(object sender, EventArgs e)
        {
            txtkehu.Text = stock.CustomName;
            txtganghao.Text = stock.GH;
            txthetonghao.Text = stock.ContractNum;
            txtordernum.Text = stock.orderNum;
            txtmenfu.Text = stock.MF;
            txtpingming.Text = stock.PM;
            txtyanse.Text = stock.YS;
            txtkucunjuanshu.Text = stock.MS.ToString();
            txtkucunmingshu.Text = stock.JS.ToString();
            txtkezhong.Text = stock.KZ;
            txtkuanhao.Text = stock.kuanhao;
            txtchengfeng.Text = stock.CF;
            txtcangku.Text = stock.CKMC;
            txtbianhao.Text = stock.BH;
            txtguige.Text = stock.GG;
            txthuahao.Text = stock.Huahao;
            txtkehupingming.Text = stock.CustomerPingMing;
            txtkehusehao.Text = stock.CustomerColorNum;
            cmbjiazhi.Text = stock.Kuwei;
            txtYingwenming.Text = dbService.GetOnedb(x => x.bh == stock.BH).EnglishName;
            comdanwei.Text = "米";
            var d = stock;
            juanHaoTables = new BindingList<JuanHaoTable>(new StockHelper().加载卷(d));
            gridControl1.DataSource = juanHaoTables;
            var lxr = LXRService.GetOneLXR(x => x.MC == stock.CustomName);
            var maitou = MaitouService.GetOneMaitou(x => x.khbh == lxr.BH).path;
            if (string.IsNullOrWhiteSpace(maitou))
            {
                cmbmaitou.Text = cmbmaitou.Items[0].ToString();
            }
            else
            {
                cmbmaitou.Text = maitou;
            }
            txtheji.Text = juanHaoTables.Sum(x => x.biaoqianmishu).ToString();
            txthejijuanshu.Text = (juanHaoTables.Count - 1).ToString();
            if (string.IsNullOrWhiteSpace(stock.LiuzhuanCard))
            {
                txtMalv.Text = lxr.Mashu.ToString("N0");
            }
            else
            {
                var liuzhuanka = LiuzhuancardService.GetOneLiuzhuancard(x => x.CardNum == stock.LiuzhuanCard);
                if (!string.IsNullOrWhiteSpace(liuzhuanka.CardNum))
                {
                    txtMalv.Text = liuzhuanka.MaShu.ToString();
                }
            }
            if (juanHaoTables.Count > 0)
            {
                if (juanHaoTables[0].MaShu != txtMalv.Text.ToDecimal(0))
                {
                    if (Tools.ShowMessageBox.ShowAskBox("流转卡设定的挂码数和已经打好卷的挂码数不一致！是否把挂码数设置成已经打好卷的挂码数") == DialogResult.Yes)
                    {
                        txtMalv.Text = juanHaoTables[0].MaShu.ToString("N0");
                    }
                }
            }
            juanHaoTables.ForEach(x => x.biaoqianmishu = x.biaoqianmishu * x.MaShu / 100 / txtMalv.Text.ToDecimal(0) * 100);
            juanHaoTables.ForEach(x => x.MaShu = txtMalv.Text.ToDecimal(100));
            gridControl1.RefreshDataSource();
            //= !=string.Empty ? : MaitouService.GetOneMaitou(x => x.khbh == stock.CustomName).path;
        }

        private void 确定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            if (string.IsNullOrWhiteSpace(comdanwei.Text))
            {
                Tools.ShowMessageBox.ShowErrorBox("请选择一下卷单位!");
                return;
            }
            if (txtMalv.Text.ToDecimal() < 60)
            {
                Sunny.UI.UIMessageBox.ShowWarning("码数请填写整数  比如98码就填98 不能填0.98");
                return;
            }
            ///检查架子号的输入
            if (!string.IsNullOrWhiteSpace(cmbjiazhi.Text))
            {
                if (cmbjiazhi.Text.Split('-').Length != 2)
                {
                    Sunny.UI.UIMessageBox.ShowError("架子号的输入只能是归属公司-架子号，\r\n架子号的输入格式错误");
                    return;
                }
                if (!BLL.库存BLL.检查架子号(cmbjiazhi.Text))
                {
                    Sunny.UI.UIMessageBox.ShowError("该架子号在架子资料中没有找到相关信息，\r\n请到架子资料里面新增一下");
                    return;
                }
            }
            if (juanHaoTables.FirstOrDefault(x => x.biaoqianmishu == 0) != null)
            {
                Sunny.UI.UIMessageBox.ShowError("存在标签米数是0的现象！\r\n保存失败");
                return;
            }
            bool IsHave = false;
            try
            {
                Connect.dbcontext.BeginTran();
                foreach (var j in juanHaoTables)
                {
                    j.Danwei = comdanwei.Text;
                    if (string.IsNullOrWhiteSpace(j.JuanHao))
                    {
                        IsHave = true;
                        j.JuanHao = BianhaoBLL.CreatJuanhao(stock.GH, j.PiHao.ToString());
                        j.MiShu = j.biaoqianmishu * txtMalv.Text.ToDecimal() / 100;
                        j.rq = DateTime.Now;
                        j.SumKouFeng = 0;
                    }
                    j.SampleNum = stock.BH;
                    j.SampleName = stock.PM;
                    j.CustomerName = stock.CustomName;
                    j.GangHao = stock.GH;
                    j.guige = stock.GG;
                    j.Houzhengli = stock.houzhengli;
                    j.kuanhao = stock.kuanhao;
                    j.OrderNum = stock.orderNum;
                    j.MaShu = txtMalv.Text.TryToDecmial(0);
                    j.yanse = stock.YS;
                    j.Huahao = stock.Huahao;
                    j.Menfu = stock.MF;
                    j.Kezhong = stock.KZ;
                    j.CustomerColorNum = stock.CustomerColorNum;
                    j.CustomerName = stock.CustomName;
                    j.CustomerPingMing = stock.LiuzhuanCard;
                    j.ColorNum = stock.ColorNum;
                    j.Ckmc = stock.CKMC;
                    j.Hetonghao = stock.ContractNum;
                    j.ReceiptNo = stock.RKDH;
                    if (IsHave)
                    {
                        Connect.dbcontext.Insertable(j).ExecuteCommand();
                    }
                    else
                    {
                        Connect.dbcontext.Updateable(j).ExecuteCommand();

                    }
                }
                if (comdanwei.Text == "米")
                {
                    stock.yijianmishu = txtheji.Text.ToDecimal(0) * txtMalv.Text.TryToDecmial(0) / 100 + juanHaoTables.Sum(x => x.JiaJian);
                    stock.biaoqianmishu = txtheji.Text.ToDecimal(0);
                    stock.yijianjuanshu = txthejijuanshu.Text.ToDecimal(0);
                }
                else
                {
                    stock.yijianmishu = (decimal)0.9144 * txtheji.Text.ToDecimal(0) * txtMalv.Text.TryToDecmial(0) / 100 + juanHaoTables.Sum(x => x.JiaJian);
                    stock.biaoqianmishu = (decimal)0.9144 * txtheji.Text.ToDecimal(0);
                    stock.yijianjuanshu = txthejijuanshu.Text.ToDecimal(0);

                }
                stock.Kuwei = cmbjiazhi.Text;
                stock.Difference = stock.RukuNum - stock.biaoqianmishu;
                string message = "布料名为" + txtpingming.Text + "  颜色为 " + txtyanse.Text + " 订单号为" + txtordernum.Text + " 缸号为" + txtganghao.Text + "是否已经全部检验打卷完毕";
                if (Sunny.UI.UIMessageBox.ShowAsk(message))
                {
                    stock.IsCheckDone = " 已结束";
                    stock.MS = stock.biaoqianmishu;
                    stock.JS = stock.yijianjuanshu;
                }
                else
                {
                    stock.IsCheckDone = " 未结束";
                }
                Connect.dbcontext.Updateable(stock).ExecuteCommand();
                Connect.dbcontext.CommitTran();
                this.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存的时候发送错误！有可能是一个数据都没有" + ex.Message, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
                Connect.dbcontext.RollbackTran();
            }
        }
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.DeleteRow(gridView1.FocusedRowHandle);
            juanHaoTables.RemoveAt(gridView1.FocusedRowHandle);
            txtheji.Text = juanHaoTables.Sum(x => x.biaoqianmishu).ToString();
            txthejijuanshu.Text = (juanHaoTables.Count).ToString();
        }
        private JuanHaoTable CreatJuan()
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var j = new JuanHaoTable();
                j.Danwei = comdanwei.Text;
                j.JuanHao = BianhaoBLL.CreatJuanhao(stock.GH, j.PiHao.ToString());
                j.MiShu = juanHaoTables[gridView1.FocusedRowHandle].biaoqianmishu;
                j.SampleNum = stock.BH;
                j.SampleName = stock.PM;
                j.CustomerName = stock.CustomName;
                j.GangHao = stock.GH;
                j.guige = stock.GG;
                j.Houzhengli = stock.houzhengli;
                j.kuanhao = stock.kuanhao;
                j.OrderNum = stock.orderNum;
                j.MaShu = txtMalv.Text.TryToDecmial(0);
                j.rq = DateTime.Now;
                j.SumKouFeng = 0;
                j.yanse = stock.YS;
                j.Huahao = stock.Huahao;
                j.biaoqianmishu = juanHaoTables[gridView1.FocusedRowHandle].biaoqianmishu;
                j.PiHao = juanHaoTables[gridView1.FocusedRowHandle].PiHao;
                j.Huahao = txthuahao.Text;
                j.CustomerColorNum = txtkehusehao.Text;
                j.CustomerPingMing = txtkehupingming.Text;
                j.ColorNum = txtsehao.Text;
                j.Menfu = txtmenfu.Text;
                j.Kezhong = txtkezhong.Text;
                j.Hetonghao = txthetonghao.Text;
                j.ReceiptNo = stock.RKDH;
                j.Ckmc = stock.CKMC;
                return j;
            }
            else
            {
                return new JuanHaoTable();
            }
        }
        private void 直接打印ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            var fm = new 打印设置窗体();
            fm.ShowDialog();
            foreach (var s in gridView1.GetSelectedRows())
            {
                gridView1.FocusedRowHandle = s;
                new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Print, moban = PrintPath.唛头模板 + cmbmaitou.Text, juan = CreatJuan() }.打印();
            }
        }

        private void 码单编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (后整理管理系统.自定义类.PrintService.CheckPrintDesignAccess())
            {
                gridView1.CloseEditor();
                var fm = new 打印设置窗体();
                //fm.ShowDialog();
                new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Design, moban = PrintPath.唛头模板 + cmbmaitou.Text, juan = CreatJuan() }.打印();
            }
        }

        private void 码单预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            var fm = new 打印设置窗体();
            //fm.ShowDialog();
            new Tools.打印唛头() { copyies = fm.copyies, PrinterName = fm.printer, userful = PrintModel.Privew, moban = PrintPath.唛头模板 + cmbmaitou.Text, juan = CreatJuan() }.打印();
        }

        private void 转98码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(txtMalv.Text.ObjToDecimal()==0)
            {
                ShowMessageBox.ShowErrorBox("转码的码数不能为0");
                return;
            }
            gridControl1.RefreshDataSource();
            foreach (var j in juanHaoTables)
            {
                j.MaShu = j.MaShu == 0 ? stock.MaShu : j.MaShu;
                j.biaoqianmishu = j.biaoqianmishu * j.MaShu / 100 / txtMalv.Text.ToDecimal(0) * 100;
                j.MaShu = txtMalv.Text.ToDecimal(100);
                j.biaoqianmishu = Math.Round(j.biaoqianmishu, 0);
            }
            txtheji.Text = juanHaoTables.Sum(x => x.biaoqianmishu).ToString();
            gridControl1.RefreshDataSource();
        }
        private void 加载架子()
        {
            foreach (var n in JiaziTableService.GetJiaziTablelst(x => x.State == "自己公司"))
            {
                cmbjiazhi.Items.Add(n.JiaziID + "-" + n.Guisuo);
            }
        }
    }
}
